<?php

namespace app\admin\controller\litestore;

use app\common\controller\Backend;
use app\admin\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use fast\Tree;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Litestoregoodsspec extends Backend
{
    
    /**
     * Litestoreorder模型对象
     * @var \app\admin\model\Litestoreorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\litestore\Litestoregoodsspec;


        $Litestorecategory = new \app\admin\model\litestore\Litestorecategory;
        $tree = Tree::instance();
        $tree->nbsp = "";
        $tree->init(collection($Litestorecategory->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [];
        foreach ($this->categorylist as $k => $v)
        {
            $categorydata[$v['id']] = $v;
        }
        
        $categorylist2 =$tree->getTreeArray(0, 'name');
     
 
        $this->assignconfig('typeList', $categorylist2);
        $this->view->assign("parentList", $categorydata);

        $all = collection($Litestorecategory->order("weigh desc,id desc")->select())->toArray();

        foreach ($all as $k => &$v) {
           
            $channelList[] = [
                'id'       => $v['id'],
                'parent'   => $v['pid'] ?: '0',
                'text'     => htmlentities(__($v['name'])),
                'expand'   => true,
                'disabled' => false,
                'state'    => 0
            ];
           
        }
        
         $this->assignconfig('channelList', $channelList);
       
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function chosegoods(){
         //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['good'])
                    ->where($where)
                    ->order('good.goods_sort desc,good.goods_id desc')
                    ->count();

             $list = $this->model
                    ->with(['good'])
                    ->where($where)
                    ->order('good.goods_sort desc,good.goods_id desc')
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        
   
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['good'])
                    ->where($where)
                    ->order('good.goods_sort desc,good.goods_id desc')
                    ->count();

             $list = $this->model
                    ->with(['good'])
                    ->where($where)
                    ->order('good.goods_sort desc,good.goods_id desc')
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        
   
        return $this->view->fetch();
    }


     /**
     * 查看
     */
    public function index3()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['good'])
                    ->where($where)
                    ->order('good.goods_sort desc,good.goods_id desc')
                    ->count();

             $list = $this->model
                    ->with(['good'])
                    ->where($where)
                    ->order('good.goods_sort desc,good.goods_id desc')
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        
   
        return $this->view->fetch();
    }
     /**
     * 查看
     */
    public function index2()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $today = date('Y-m-d');
            $future15 = date('Y-m-d', strtotime('+15 days'));
            $total = $this->model
                ->with(['good'])
                ->where(function($query) use ($today, $future15) {
                    $query->where('fa_litestore_goods_spec.daoqi', '<', $today)
                          ->whereOr('fa_litestore_goods_spec.daoqi', 'between', [$today, $future15]);
                })
                ->order('good.goods_sort desc,good.goods_id desc')
                ->count();

            $list = $this->model
                ->with(['good'])
                ->where(function($query) use ($today, $future15) {
                    $query->where('fa_litestore_goods_spec.daoqi', '<', $today)
                          ->whereOr('fa_litestore_goods_spec.daoqi', 'between', [$today, $future15]);
                })
                ->order('good.goods_sort desc,good.goods_id desc')
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        
   
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function edit2($spcid = null)
    {
        $row = $this->model->get($spcid);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $baojia = [];
            if (!empty($row['baojia'])) {
                $baojia = json_decode($row['baojia'],true);
            }

         


            $bajia_key = Db::table('fa_pifa_baojia')->select();


            foreach ($bajia_key as $key => $value) {
                if (!isset($baojia[$value['id']])) {
                   $baojia[$value['id']] = 0;
                }
            }
           
            $this->view->assign('row', $row);
            $this->view->assign('baojia', $baojia);
            $this->view->assign('bajia_key', $bajia_key);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['baojia'] = json_encode($params['baojia']);
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 添加
     */
    public function edit3($spcid = null)
    {
        $row = $this->model->get($spcid);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $baojia = [];
            if (!empty($row['baojia_quyu'])) {
                $baojia = json_decode($row['baojia_quyu'],true);
            }

            

            $shangjia = Db::table('fa_pifa_shangjia')->select();


            $bajia_key = Db::table('fa_pifa_baojia')->select();


            $baojia_list = [];

            foreach ($shangjia as $key => $value) {
                $baojia_list[$value['id']] = [];
                foreach ($bajia_key as $key1 => $value1) {
                    if (!isset($baojia[$value['id']][$value1['id']])) {
                       $baojia_list[$value['id']][$value1['id']] = 0;
                    }else{
                        $baojia_list[$value['id']][$value1['id']] = $baojia[$value['id']][$value1['id']];
                    }
                }
            }


          
            
          
            $this->view->assign('row', $row);
            $this->view->assign('baojia', $baojia_list);
            $this->view->assign('shangjia', $shangjia);
            $this->view->assign('bajia_key', $bajia_key);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['baojia_quyu'] = json_encode($params['baojia_quyu']);
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
    
}
